import React, { useState, useEffect, useRef } from "react";
import { Popconfirm, Button, Image, message } from "antd";
import { PageContainer, FooterToolbar } from "@ant-design/pro-layout";
import ProCard from "@ant-design/pro-card";
import { LeftOutlined } from "@ant-design/icons";
import ProTable from "@ant-design/pro-table";
import ProForm, {
  ProFormList,
  ProFormSelect,
  ProFormText,
} from "@ant-design/pro-form";
import { history, useLocation } from "umi";
import {
  checkGroupBag,
  getBagListByGroupId,
  batchAdd,
  batchUpdate,
} from "@/api/package";
import { filterRasCode } from "@/const";

export default () => {
  const { categoryId, specId, groupId, edit } = useLocation().query;
  const [loading, setLoading] = useState(false);
  const [info, setInfo] = useState();
  const getList = async () => {
    setLoading(true);
    const res = await getBagListByGroupId({
      groupId,
    });
    setLoading(false);
    if (res.data) {
      formRef.current.setFieldsValue({
        ...res.data,
        // bagList: res.data.bagList.slice(0, 1),
      });
      setInfo(res.data);
    }
  };

  useEffect(() => {
    getList();
  }, []);

  const formRef = useRef();

  const handleAddOrUpdate = async (fields) => {
    const postData = {
      ...fields,
      categoryId,
      groupId,
      specId,
    };
    let func = edit ? batchUpdate : batchAdd;
    const res = await func(postData);
    if (res.code == 200) {
      message.success(edit ? "编辑成功" : "新增成功");
      history.goBack();
    }
  };

  return (
    <PageContainer
      loading={loading}
      header={{
        title: (
          <div className="pointer" onClick={() => history.goBack()}>
            <LeftOutlined style={{ marginRight: 10 }} />
            {edit ? "编辑" : "新增"}书包
          </div>
        ),
        breadcrumb: {},
      }}
    >
      <ProForm
        layout="vertical"
        formRef={formRef}
        onFinish={async (values) => {
          return handleAddOrUpdate(values);
        }}
        submitter={{
          render: (props, dom) =>
            !loading && info?.bagList?.length ? (
              <FooterToolbar>{dom[1]}</FooterToolbar>
            ) : null,
        }}
      >
        <ProCard ghost style={{ marginTop: 20 }}>
          <ProFormList
            name="bagList"
            copyIconProps={false}
            deleteIconProps={false}
            creatorButtonProps={false}
            itemRender={({ listDom, action }, { index }) => (
              <ProCard
                bordered
                style={{ marginBlockEnd: 20 }}
                title={
                  <>
                    <ProFormText
                      label={`第${index + 1}期书包号`}
                      width="lg"
                      name="bagRasUrl"
                      onChange={async (e) => {
                        const bagCode = filterRasCode(e.target.value);
                        formRef.current.setFieldValue(
                          ["bagList", index, "bagCode"],
                          bagCode
                        );
                      }}
                      rules={[
                        { required: true, message: "请输入书包号" },
                        {
                          max: 50,
                          message: "最长为50位",
                        },
                      ]}
                    />
                    <ProFormText hidden={true} name="bagCode" />
                  </>
                }
                extra={action}
                bodyStyle={{ paddingBlockEnd: 0 }}
              >
                {listDom}
              </ProCard>
            )}
          >
            {(_, index1, action1) => {
              return (
                <ProFormList
                  name="storageBooks"
                  copyIconProps={false}
                  deleteIconProps={false}
                  creatorButtonProps={false}
                >
                  {(_, index2, action2) => {
                    return (
                      <ProForm.Group>
                        <Image
                          width={60}
                          height={60}
                          src={
                            info?.bagList?.[index1]?.storageBooks?.[index2]
                              ?.picture
                          }
                        ></Image>
                        <span>
                          {
                            info?.bagList?.[index1]?.storageBooks?.[index2]
                              ?.title
                          }
                        </span>
                        <ProFormText
                          name="storageBookRasUrl"
                          width="lg"
                          placeholder="请扫码/输入书籍码"
                          onChange={async (e) => {
                            const rasCode = filterRasCode(e.target.value);
                            formRef.current.setFieldValue(
                              [
                                "bagList",
                                index1,
                                "storageBooks",
                                index2,
                                "storageBookRasCode",
                              ],
                              rasCode
                            );
                          }}
                          rules={[
                            { required: true, message: "请扫码/输入书籍码" },
                            {
                              max: 50,
                              message: "最长为50位",
                            },
                            {
                              validator: async (_, value) => {
                                if (!value) return;
                                const rasCode = filterRasCode(value);
                                const res = await checkGroupBag({
                                  schoolbagBookId:
                                    info?.bagList?.[index1]?.storageBooks?.[
                                      index2
                                    ]?.bookId,
                                  bookRasCode: rasCode,
                                  bookRsaUrl: value,
                                });
                                if (res.data) {
                                  return Promise.resolve();
                                } else {
                                  return Promise.reject(
                                    new Error("书籍码不匹配")
                                  );
                                }
                              },
                            },
                          ]}
                        />

                        <ProFormText
                          hidden={true}
                          name="storageBookRasCode"
                          width="lg"
                        />
                      </ProForm.Group>
                    );
                  }}
                </ProFormList>
              );
            }}
          </ProFormList>
        </ProCard>
      </ProForm>
    </PageContainer>
  );
};
